package cn.tedu.luban.order.webapi.utils;

import cn.tedu.luban.commons.exception.LubanServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.springframework.stereotype.Service;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class IncUidGenerator  {

    private static final String IP = getIp();

    private static final AtomicInteger COUNT = new AtomicInteger(0);

    /**
     * 订单编号生成
     * 12位时间戳 + 当前服务器原子性自增长3位 + 当前服务器ip后三位 + 当前用户最后1位
     *
     * @param userId 用户id
     * @return {@link String}
     * @throws LubanServiceException 业务异常
     */
    public String generate(Long userId) throws LubanServiceException {
        long start = System.currentTimeMillis() % 100000000000L;
        int andIncrement = COUNT.getAndIncrement();
        if (COUNT.get() >= 999) {
            COUNT.set(0);
        }
        int ipLastInt = Integer.parseInt(IP);
        String orderNo = start + String.format("%03d", andIncrement) + String.format("%03d", ipLastInt);
        return orderNo + userId % 10;
    }

    private static List<String> getHostAddress() throws SocketException {
        List<String> ipList = new ArrayList<>(5);
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            Enumeration<InetAddress> allAddress = ni.getInetAddresses();
            while (allAddress.hasMoreElements()) {
                InetAddress address = allAddress.nextElement();
                if (address.isLoopbackAddress()) {
                    // skip the loopback addr
                    continue;
                }
                if (address instanceof Inet6Address) {
                    // skip the IPv6 addr
                    continue;
                }
                String hostAddress = address.getHostAddress();
                ipList.add(hostAddress);
            }
        }
        return ipList;
    }

    private static String getIp() {
        String ip = null;
        try {
            List<String> ipList = getHostAddress();
            // default the first
            ip = (!ipList.isEmpty()) ? ipList.get(0) : "";
        } catch (Exception ex) {
            log.warn("Utils get IP warn", ex);
        }

        if (StringUtils.isEmpty(ip)) {
            return "999";
        }
        return ip.split("\\.")[3];
    }
}
